﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Unread.Business.Services.Interfaces;
using Unread.Notifications.Models;
using Unread.Notifications.Services.Interfaces;
using Windows.ApplicationModel.Background;
using Windows.UI.StartScreen;

namespace Unread.BackgroundTasks
{
    public sealed class NotificationBackgroundTask : IBackgroundTask
    {
        private readonly IUnreadFeedItemLoader _unreadFeedItemLoader;
        private readonly ITileUpdater _tileUpdater;
        private readonly ISecondaryTileUpdater _secondaryTileUpdater;

        public NotificationBackgroundTask()
        {
            Bootstrapper.Run();

            _unreadFeedItemLoader = (IUnreadFeedItemLoader)ServicesFactory.GetUnreadFeedItemLoader();
            _tileUpdater = (ITileUpdater)ServicesFactory.GetTileUpdater();
            _secondaryTileUpdater = (ISecondaryTileUpdater)ServicesFactory.GetSecondaryTileUpdater();
        }

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var _deferral = taskInstance.GetDeferral();

            await UpdatePrimaryTile();
            await UpdateSecondaryTiles();

            _deferral.Complete();
        }

        private async Task UpdatePrimaryTile()
        {
            var totalUnreadItems = await _unreadFeedItemLoader.LoadTotalCount();

            if (totalUnreadItems > 0)
            {
                var request = new TileUpdateRequest 
                { 
                    LargeText = totalUnreadItems.ToString(), RegularText = "Unread", Delay = TimeSpan.FromSeconds(5) 
                };
                _tileUpdater.Update(request);
            }
        }

        private async Task UpdateSecondaryTiles()
        {
            var secondaryTiles = await SecondaryTile.FindAllAsync();
            if (!secondaryTiles.Any())
                return;

            foreach (var secondaryTile in secondaryTiles)
            {
                var feedId = new Guid(secondaryTile.TileId);
                var totalUnreadItems = await _unreadFeedItemLoader.LoadTotalCount(feedId);

                if (totalUnreadItems > 0)
                {
                    var request = new SecondaryTileUpdateRequest 
                    { 
                        TileId = secondaryTile.TileId, LargeText = totalUnreadItems.ToString(), RegularText = secondaryTile.ShortName, Delay = TimeSpan.FromSeconds(5) 
                    };
                    _secondaryTileUpdater.Update(request);
                }
            }
        }
    }
}
